<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @package     Pages Module
 * @author      Matrix Infoline (infolinematrix@gmail.com
 * @copyright   (c) Matrix Infoline
 */

class Login extends Frontend_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->template->set_layout('full_layout');
		$this->template->set_partial('header', 'header/header');
        $this->template->set_partial('footer', 'footer/footer');
        $this->load->library('Facebook');
		$this->load->driver('session');
		
		$this->load->library('parser');
	}

	public function index()
	{
		
		$this->facebook->destroySession();
		
		$data['fbUrl']= $this->facebook->getLoginURL();
		$user=$this->facebook->getUser();
	
		if ($user) {
			$user_profile = $this->facebook->api('/me');
		
			$email = $user_profile['id'];
			$name = $user_profile['name'];
			$identity = 'FB';
		
		
			if($this->member_model->checkIdentity($email)== TRUE) {
		
				//-- Redirect to Dashboard ---//
				$em=$email;
				$sql="select * from member where email='$em'";
				$query = $this->db->query($sql);
				$user = $query->row();
		
				//print_r($user);
				//die();
		
				if ($user){
		
					//$this->member_model->clear_session_data("member");
		
					write_session('mem_id', $user->id);
					write_session('mem_email', $user->email);
					write_session('mem_password', $user->password);
					write_session('mem_name', $user->name);
					write_session('mem_last_login_date', $user->last_login_date);
					write_session('mem_last_login_ip', $user->last_login_ip);
					write_session('mem_created_on', $user->created_on);
					//-- Update last login of successfull Login
					$sql = "update member set last_login_date = NOW() where email='$user->email'";
					$query = $this->db->query($sql);
		
					redirect('member/dashboard');
				}
			}
			else{
				//else store data to member table and redirect to dashboard//--
		
				$post_data=array(
						'email' =>	$email,
						'name' =>	$user_profile['name'],
						'last_login_ip'=>get_ip(),
						'created_on'=> date('Y-m-d H:i:s'),
						'last_login_date'=> date('Y-m-d H:i:s'),
						'identity' => $identity,
						'status' => '51'
				);
		
		
		
				$this->db->insert('member',$post_data);
		
				if($this->member_model->checkIdentity($email)== TRUE) {
		
					//-- Redirect to Dashboard ---//
					$em=$email;
					$sql="select * from member where email='$em'";
					$query = $this->db->query($sql);
					$user = $query->row();
		
					//print_r($user);
					//die();
		
					if ($user){
		
						$this->member_model->clear_session_data("member");
		
						write_session('mem_id', $user->id);
						write_session('mem_email', $user->email);
						write_session('mem_password', $user->password);
						write_session('mem_name', $user->name);
						write_session('mem_last_login_date', $user->last_login_date);
						write_session('mem_last_login_ip', $user->last_login_ip);
						write_session('mem_created_on', $user->created_on);
						//-- Update last login of successfull Login
						$sql = "update member set last_login_date = NOW() where email='$user->email'";
						$query = $this->db->query($sql);
		
						redirect('member/dashboard');
					}
				}
		
			}
		
		}
		
		
		$data['title'] = "Member Login";
		//BREADCRUMB//
		$this->template->set_breadcrumb('Home', base_url().location());
		$this->template->set_breadcrumb('Member', 'member/login');
		$this->template->set_breadcrumb('Login');

		$this->template->build('login',$data);
			
	}


	public function submit(){

		$this->form_validation->set_rules('login_email', 'Login Email', 'trim|required|valid_email');
		$this->form_validation->set_rules('login_password', 'Password', 'trim|required|min_length[4]');
		

		if ($this->form_validation->run() == true) {
			$post_data = array(
					'email' => trim($_POST['login_email']),
					'password' => trim($_POST['login_password']));

			//	var_dump($post_data);die();
				
			if($this->member_model->check_login_submit($post_data) == TRUE){
				redirect('member/dashboard');
			}else{
				$this->session->set_flashdata('msg', "Invalid login ..");
				redirect('member/login');
			}
		}else{
			$this->index();
		}

	}

	function out()
	{
		
		$this->session->sess_destroy();
		
		$this->member_model->clear_session_data("member");

		redirect('member/login');
	}

	function register()
	{
		$this->form_validation->set_rules('full_name', 'Full Name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('email_address', 'Email', 'trim|required|valid_email|is_unique[member.email]');
		$this->form_validation->set_rules('password','Password','trim|required|xss_clean|min_length[6]');
		$this->form_validation->set_rules('agree', 'I agree the Terms and Conditions', 'trim|required');
		$this->form_validation->set_message('full_name', 'Full Name filed is required.');
		if ($this->form_validation->run() == true) {
				
			$post_data = array(
					'name' => $this->input->post('full_name'),//$this->input->post('full_name'),
					'email' => $this->input->post('email_address'),//$this->input->post('textemail'),
					'password' => $this->input->post('password'),
					'created_on'=> date('Y-m-d H:i:s'),
					'last_login_ip'	=> get_ip(),
					'agree'=>$this->input->post('agree'),
					'status' => '1',
					'activationcode' => md5($this->input->post('email_address').time()),
		
			);

			//var_dump($post_data);die();
			
			if($this->member_model->check_login_submit($post_data)== true){
				$this->login();

			}else{

				$this->db->insert('member',$post_data);

				//--Send Confirmation Email Due to the server upload--//
				$variable = 'registration_confirm';
				
				$email_template = $this->member_model->getTemplatebyType($variable);

				
				//var_dump($email_template);die();
				
				$member_master = $this->member_model->getMemberbyemail($this->input->post('email_address'));

				$member_name = $member_master->name;
				$member_email = $member_master->email;
				$member_pass = $member_master->password;

				write_session('regEmail',$member_email);
				write_session('regPass',$member_pass);
				
				$website = $this->member_model->getWebconfiguration('web_title');
				$cutomer_care = $this->member_model->getWebconfiguration('call_now');
				$email_subject = $email_template->title;
				//var_dump($email_subject);die();
				$email_body = $email_template->description;

				$key = $member_master->activationcode;


				$confirm = "<p><a href='".base_url()."member/login/activationcode/$key' >


				http://yellowpagesphpscript.com/demo/v4/member/login/activationcode/$key</a>


				</p>";

				$data = array(
						'member_name' => $member_name,
						'confirm' => $confirm,
						'website' => $website,
						'customer_care_no' => $cutomer_care

				);

				$this->load->library('parser');
				$message = $this->parser->parse_string($email_body, $data, TRUE);
				//$message .= "<p><a href='".base_url()."member/$key' >Click here</a> to confirm your account</p>";
				
				$this->member_model->send_mail($member_email, $email_subject, $message);

				

				$msg = "<div class='alert alert-success'> Thank You for resgister! Please Check Your Email...</div>";
				$this->session->set_flashdata('message', $msg);
				redirect('member/login');
			}
		}else{

			$this->index();
		}

	}

	function activationcode($link){
	//	die($link);
		$sql = "update member set status=51 where activationcode='$link'";
		$this->db->query($sql);
		
		$post_data = array(
				'email' => get_session('regEmail'),
				'password' => get_session('regPass')
				);
		
		//	var_dump($post_data);die();
		
		if($this->member_model->check_login_submit($post_data) == TRUE){
			redirect('member/dashboard');
		}else{
			$this->session->set_flashdata('msg', "Invalid login ..");
			redirect('member/login');
		}
	//	redirect('member/dashboard');
	}

}
